package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     *
     * @param ex
     * @param response
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex, HttpServletResponse response) {
        String message = ex.getMessage();
        log.error("异常信息：{}", message);
        
        // 如果是JWT相关异常，设置401状态码
        if (message != null && (message.contains("JWT") || message.contains("令牌"))) {
            log.error("JWT异常：{}", message);
            response.setStatus(401);
        }
        
        return Result.error(message);
    }

    /**
     * 捕获在数据库操作中发生的异常，特别是在尝试插入或更新数据库时违反了完整性约束（如唯一性约束）
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {

        //  Duplicate entry 'Jennifer Martin' for key 'idx_username'
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);

        }

        return Result.error(MessageConstant.UNKNOWN_ERROR);

    }

}
